﻿CREATE FUNCTION [dbo].[StateFlowFromByGroup](
	@TableName sysname,
	@principal_id sysname
)RETURNS TABLE AS

RETURN(
WITH States AS (SELECT DISTINCT wf.StateFromID, wf.NameFrom, wf.StateFromPos
                                 FROM   v_StateFlow AS wf INNER JOIN
                                                t_StateFlow_Groups AS wfg ON wf.StateFromID = wfg.StateFromID AND wf.StateToID = wfg.StateToID AND 
                                                wfg.principal_id = @principal_id)
    SELECT DISTINCT TOP (100) PERCENT
			wf.StateFromID, wf.NameFrom, CONVERT(bit, ISNULL(States_1.StateFromID, 0)) AS HasAccess, wf.StateFromPos, wf.StateFlowPosFrom
    FROM  v_StateFlow AS wf LEFT OUTER JOIN
                   States AS States_1 ON States_1.StateFromID = wf.StateFromID
		WHERE wf.TableNameFrom = @TableName
    ORDER BY wf.StateFromPos
)




